/*
 * @Description: 元数据上下文
 * @Author: Rfan
 * @Date: 2022-05-28 12:10:37
 * @LastEditTime: 2022-06-20 17:34:13
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { Modal } from 'antd';
import {
  ADD_DICTIONARY,
  ADD_DICTIONARY_ITEM,
  DELETE_DICTIONARY,
  DELETE_DICTIONARY_ITEM,
  EDIT_DICTIONARY_ITEM,
  SET_DICTIONARY_ITEM_LIST,
  SET_DICTIONARY_LIST,
  SET_SELECTED_ITEM,
  SET_SELECT_AT,
  SET_SELECT_DICTIONARY,
  SET_SELECT_FOND,
  EDIT_DICTIONARY
} from '../constants';
import { DictionaryReducer } from '../reducers/DictionaryReducer';
import {
  addDicItem,
  addDicType,
  deleteDicItem,
  deleteDicType,
  editDicItem,
  editDicType,
  fetchDicItemListByPage,
  fetchDicList
} from '@/api/rulesettings/dictionary';

const initialState = {
  // 当前选中的项目
  selectFond: {},
  selectAT: {},

  selectDictionary: {},

  // 字典列表
  dictionaryList: [],
  // 字典内的项目列表
  dictionaryItemList: [],
  // 选中的表格条目
  selectItems: [],

  // -------- 字典 --------
  // 状态列表
  stateList: [
    { id: 0, name: '正常' },
    { id: 1, name: '停用' }
  ]
};

const DictionaryContext = createContext();

const DictionaryContextProvider = (props) => {
  const [state, dispatch] = useReducer(DictionaryReducer, initialState);

  const actions = {
    /**
     * @description: 设置选中的全宗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },
    /**
     * @description: 设置选中的字典
     */
    setDictionary(data) {
      dispatch({ type: SET_SELECT_DICTIONARY, data });
    },

    /**
     * @description: 表格选中的项目
     * @param {*} selectArr 选中的项目
     */
    setSelectedItem(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 请求字典列表方法
     * @param {object} params 请求参数
     * @return {*}
     */
    getDictionaryList(params) {
      return new Promise((resolve, reject) => {
        fetchDicList(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_DICTIONARY_LIST, data });
            if (data && data.length > 0) {
              dispatch({ type: SET_SELECT_DICTIONARY, data: data[0] });
            }

            resolve(data);
          })
          .catch((err) => {
            console.log(err);
            dispatch({ type: SET_DICTIONARY_LIST, data: [] });
            dispatch({ type: SET_SELECT_DICTIONARY, data: {} });
            reject(err);
          });
      });
    },

    /**
     * @description: 添加字典方法
     * @param {*} params 添加的参数
     * @return {*}
     */
    addDictionaryFunc(params) {
      return new Promise((resolve, reject) => {
        addDicType(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: ADD_DICTIONARY, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 添加字典方法
     * @param {*} params 添加的参数
     * @return {*}
     */
    editDictionaryFunc(params) {
      return new Promise((resolve, reject) => {
        editDicType(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: EDIT_DICTIONARY, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 删除字典方法
     * @param {*} id
     */
    deleteDictionaryFunc(id, confirmContent = '是否删除该字典类型') {
      Modal.confirm({
        title: '删除',
        content: confirmContent,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteDicType(ids).then((res) => {
            const data = res.data.map((id) => parseInt(id, 10));
            dispatch({ type: DELETE_DICTIONARY, ids: data });
          });
        },
        onCancel() {}
      });
    },

    /**
     * @description: 请求字典内项目列表
     * @param {object} params 请求参数
     * @return {*}
     */
    getDicItemListByPage(params) {
      return new Promise((resolve, reject) => {
        fetchDicItemListByPage(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_DICTIONARY_ITEM_LIST, data: data.results });

            resolve(data);
          })
          .catch((err) => {
            console.log(err);
            dispatch({ type: SET_DICTIONARY_ITEM_LIST, data: [] });
            reject(err);
          });
      });
    },

    /**
     * @description: 情况字典列表，主要用于切换档案类型时
     */
    clearDicItemList() {
      dispatch({ type: SET_DICTIONARY_ITEM_LIST, data: [] });
    },

    addDicItemFunc(params) {
      return new Promise((resolve, reject) => {
        addDicItem(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: ADD_DICTIONARY_ITEM, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    editDicItemFunc(params) {
      return new Promise((resolve, reject) => {
        editDicItem(params)
          .then((res) => {
            const { data } = res;
            const { id } = data;
            dispatch({ type: EDIT_DICTIONARY_ITEM, data, id });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    deleteDicItemFunc(id, confirmContent = '是否删除该字典项目') {
      Modal.confirm({
        title: '删除',
        content: confirmContent,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteDicItem(ids).then((res) => {
            const data = res.data.map((id) => parseInt(id, 10));
            dispatch({ type: DELETE_DICTIONARY_ITEM, ids: data });
          });
        },
        onCancel() {}
      });
    }
  };

  const filters = {
    /**
     * @description: 单位状态过滤器
     * @param {number} code 状态Key
     * @return {string} 状态名
     */
    stateFilter(code) {
      return state.stateList.find((item) => item.id === code)?.name || '-';
    }
  };

  // watch listQuery来加载列表
  useEffect(() => {
    if (state.selectAT?.id === 0 || state.selectAT?.id) {
      actions.clearDicItemList();
      actions.getDictionaryList({ archiveTypeId: state.selectAT.id });
    }
  }, [state.selectAT]);

  return (
    <DictionaryContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </DictionaryContext.Provider>
  );
};

export const useDictionaryContext = () => {
  return useContext(DictionaryContext);
};

export { DictionaryContext, DictionaryContextProvider };
